<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/9/10
 * Time: 22:30
 * 订单
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\log\Log;
use app\common\library\Weixin;
use app\common\model\OrderShipping;
use think\Db;

class Order extends Api
{
	protected $noNeedLogin = ['notify'];
	
	/**
	 * 列表
	 */
	public function index()
	{
		$userId = $this->auth->id;
		$page = $this->request->post('page', 1, 'int');
		$status = $this->request->post('status', '', 'int');
		
		$model = new \app\common\model\Order();
		$res = $model->getOrderList($userId, $page, $status);
		$this->success('查询成功', $res);
	}
	
	/**
	 * 详情
	 */
	public function detail()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$model = new \app\common\model\Order();
		$order = $model->where(['user_id' => $this->auth->id, 'id' => $id])->find();
		!$order && $this->error('订单不存在');
		
		$goods = Db::name('orderGoods')
			->where(['order_id' => $id])
			->select();
		
		foreach ($goods as &$good) {
			$good['goods_info'] = json_decode($good['goods_info'], true);
		}
		
		$order['goods'] = $goods;
		$order['address'] = Db::name('orderAddress')->alias('oa')
			->join('area p', 'oa.province_id = p.id', 'left')
			->join('area c', 'oa.city_id = c.id', 'left')
			->join('area a', 'oa.area_id = a.id', 'left')
			->field('oa.*, p.name as province, c.name as city, a.name as area')
			->where(['oa.order_id' => $id])
			->find();
		
		$this->success('查询成功', $order);
	}
	
	/**
	 * 确认订单
	 */
	public function confirm()
	{
		$model = new \app\common\model\Order();
		$userId = $this->auth->id;
		$res = $model->createOrder($userId, $this->request->post(), 1);
		if (!$res) {
			$this->error($model->getError());
		}
		
		$where = [
			'a.user_id' => $userId,
			'a.status' => \app\common\model\Address::STATUS_NORMAL
		];
		
		$addressId = $this->request->post('address_id');
		$addressId && $where['a.id'] = $addressId;
		
		$address = $rows = Db::name('address')->alias('a')
			->join('area p', 'a.province_id = p.id', 'left')
			->join('area c', 'a.city_id = c.id', 'left')
			->join('area aa', 'a.area_id = aa.id', 'left')
			->where($where)
			->field('a.id, a.name, a.mobile, a.address, p.name as province, c.name as city, aa.name as area')
			->order(['a.is_default' => 'desc', 'a.update_time' => 'desc'])
			->find();
		
		$res['address'] = $address;
		$this->success('成功', $res);
	}
	
	/**
	 * 下单
	 */
	public function add()
	{
		$model = new \app\common\model\Order();
		$userId = $this->auth->id;
		$res = $model->createOrder($userId, $this->request->post(), 2);
		if (!$res) {
			$this->error($model->getError());
		}
		
//		$model = new \app\common\model\Order();
//		$res = $model->paySuccess($res['id']);
//
//		if($res) {
//			$this->success('支付成功');
//		} else {
//			$this->error('支付成功');
//		}
		
		if($res['amount'] > 0) {
			$config = config('weixin.' . $this->weixinPrefix);
			$weixin = new Weixin($config['app_id']);
			
			$notifyUrl = $this->request->domain() . url('api/order/notify', '', false);
			$user = \app\admin\model\User::get($userId);
			$openId = $user[$this->weixinPrefix . '_openid'];
			$data = $weixin->unifiedOrder($res['id'], $res['amount'], $notifyUrl, $openId);
			$this->success($data['msg'], $data['data'], $data['code']);
		} else {
				$this->success('支付成功', ['id' => $res['id']], 2);
		}
		
	}
	
	/**
	 * 支付
	 */
	public function pay()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$userId = $this->auth->id;
		$order = \app\common\model\Order::get($id);
		!$order && $this->error('订单不存在');
		if ($order['status'] != \app\common\model\Order::STATUS_WAIT) {
			$this->error('非待支付订单');
		}
		
		
			$config = config('weixin.' . $this->weixinPrefix);
			$weixin = new Weixin($config['app_id']);
			
			$notifyUrl = $this->request->domain() . url('api/order/notify', '', false);
			$user = \app\admin\model\User::get($userId);
			$openId = $user[$this->weixinPrefix . '_openid'];
			$data = $weixin->unifiedOrder($id, $order['amount'], $notifyUrl, $openId);
			$this->success($data['msg'], $data['data'], $data['code']);
		
	}
	
	/**
	 * 取消
	 */
	public function cancel()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$userId = $this->auth->id;
		
		$model = new \app\common\model\Order();
		$res = $model->cancel($id, $model::CANCEL_REASON_USER, $userId);
		if ($res !== false) {
			$this->success('取消成功');
		} else {
			$this->error('取消出错');
		}
	}
	
	/**
	 * 删除
	 */
	public function del()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$userId = $this->auth->id;
		
		$model = new \app\common\model\Order();
		$order = $model->where(['id' => $id, 'user_id' => $userId])->find();
		!$order && $this->error('订单不存在');
		
		$res = $model->save(['is_delete' => 1],
			['id' => $id]);
		if ($res !== false) {
			$this->success('删除成功');
		} else {
			$this->error('删除出错');
		}
	}
	
	/**
	 * 物流
	 */
	public function shipping()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$model = new OrderShipping();
		$res = $model->getShipping($id);
		$data = $res['Traces'] ??[];
		$this->success('查询成功', $data);
	}
	
	
	/**
	 * 签收
	 */
	public function sign()
	{
		$id = $this->request->post('id');
		!$id && $this->error('参数错误');
		
		$model = new \app\common\model\Order();
		
		$res = $model->sign($id);
		if ($res) {
			$this->success('签收成功');
		} else {
			$this->error('签收出错');
		}
	}
	
	/**
	 * 支付回调
	 */
	public function notify() {
		$path = 'notify'.DS;
		$res = Weixin::notify($path);
//		$res = json_decode('{"appid":"wx8baa81690abfc1a9","attach":"order","bank_type":"ICBC_CREDIT","cash_fee":"100","fee_type":"CNY","is_subscribe":"Y","mch_id":"1556575171","nonce_str":"9lcpcg4dap1ndpl7g194klp71aiu0v7e","openid":"oyVO31JNY2ocXSjLJ8qhXUhYfLg8","out_trade_no":"8-1569128643","result_code":"SUCCESS","return_code":"SUCCESS","sign":"C84A8CF1FCB74BFBD4A60A145373F4EA","time_end":"20190922130409","total_fee":"100","trade_type":"JSAPI","transaction_id":"4200000389201909220856298484"}', true);
		if($res) {
			$arr = explode('-', $res['out_trade_no']);
			$orderId = $arr[0];
			$model = new \app\common\model\Order();
			$orderRes = $model->paySuccess($orderId);
			if($orderRes) {
				Log::info('支付回调操作成功'.PHP_EOL, $path);
				$xml = "<xml>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <return_msg><![CDATA[OK]]></return_msg>
</xml>";
				echo $xml;
				die;
			} else {
				Log::info('支付回调操作失败'.PHP_EOL, $path);
			}
		}
	}
}